% Octave script: mm1.m
% Proposito:     Simula una cola M/M/1
%
% Declaracion de constantes y variables:

function nada = queuemm1(name)

clear next_event_type;
clear event_types;
clear num_custs_delayed;
clear num_delays_required;
clear num_events;
clear num_in_q;
clear server_status;
clear area_num_in_q;
clear area_server_status;
clear area_system_amount;
clear mean_interarrival;
clear mean_service;
clear time;
clear time_arrival;
clear time_last_event;
clear time_next_event;
clear total_of_delays;
clear delayinqueue;
clear times_service;
clear total_in_system;
clear L;
clear cqueue;
clear pstate;
clear tevents;
clear morethanoneminute;
clear client_arrivals;
clear client_departures;

global Q_LIMIT = 100;
global BUSY    = 1;
global IDLE    = 0;

global next_event_type;
global event_types;
global num_custs_delayed;
global num_delays_required;
global num_events;
global num_in_q;
global server_status;

global area_num_in_q;
global area_server_status;
global area_system_amount;
global mean_interarrival;
global mean_service;
global time;
global time_arrival;
global time_last_event;
global time_next_event;
global total_of_delays;
global delayinqueue;
global times_service;
global total_in_system;
global L;
global cqueue;
global tevents;
global morethanoneminute;
global client_arrivals;
global client_departures;

% Abre los archivos I/O
inpfile = fopen([name '.inp'],'r');
outfile = fopen([name '.out'],'w');
timfile = fopen([name '.tim'],'w');
tsfile = fopen([name '.ts'],'w');
qfile = fopen([name '.q'],'w');
sfile = fopen([name '.s'],'w');
dqfile = fopen([name '.dq'],'w');
stfile = fopen([name '.st'],'w');
multi = fopen([name '.mlt'],'a');

% Especifica el numero de eventos
num_events = 2;

% Almacenes de tiempos, cantidad en cola y estados
cqueue = [];
tevents = [];
pstate = [];
L = [];
event_types = [];

morethanoneminute = 0;

% Lee el archivo de entrada
xdata = fscanf(inpfile,'%f %f %f',[1 3]);
mean_interarrival   = xdata(1);
mean_service        = xdata(2);
num_delays_required = xdata(3);
 

% Escribe los encabezados de los reportes y parametros de entrada
fprintf(outfile,'Sistema de cola de servidor simple\n\n');
fprintf(outfile,'Tiempo medio entre arribos %11.3f minutos\n\n',mean_interarrival);
fprintf(outfile,'Tiempo medio de servicio   %11.3f minutos\n\n',mean_service);
fprintf(outfile,'Numero de clientes         %14d\n\n', num_delays_required);

fprintf(multi,'\n%d,%14.3f,%14.3f', num_delays_required, mean_interarrival, mean_service);


fprintf(timfile,'Series de tiempo producidas por mm1.m \n');
fprintf(timfile,'3\n');
fprintf(timfile,'time\n');
fprintf(timfile,'longitud de la cola\n');
fprintf(timfile,'ocupacion del servidor (OCUPADO=1,LIBRE=0)\n');

% Inicializa la simulacion
initialize();

% Corre la simulacion
while ( num_custs_delayed < num_delays_required )
	fprintf(timfile, "%16.3f %d %d\n",time,num_in_q,server_status);
	fprintf(tsfile, "%16.3f\n",time);
	fprintf(qfile, "%d\n",num_in_q);
	fprintf(sfile, "%d\n",server_status);
	% Determina el proximo evento
	timing();
	
	% Actualiza los acumuladores estadisticos de tiempos medios
	update_time_avg_stats();
	
	% Invoca al evento apropiado
	switch (next_event_type)
		case 1
			arrive();
			%break;
		case 2
			depart();
			%break;
	endswitch
        % actualiza los vectores con estado de la cola y evento producido
	cqueue = [cqueue num_in_q];
	pstate = [pstate server_status];
endwhile

clf;
hold on;
for i=1:num_delays_required
	% plot delay of client
	arrival = client_arrivals(i);
	delay = delayinqueue(i);
	service_time = times_service(i);
	service_start = arrival + delay;
	service_end = service_start + service_time;

	plot([arrival service_start], [i i],"1");
	plot([service_start service_end], [i i],"2");
end
hold off;
print([name 'servtotal.eps'], '-deps');

total_in_system = delayinqueue + times_service;

for i = 1:num_delays_required
	if delayinqueue(i) > 1.000
		morethanoneminute = morethanoneminute + 1;
	endif

	fprintf(dqfile, "%16.3f\n",delayinqueue(i));
	fprintf(stfile, "%16.3f\n",times_service(i));
end
% Invoca al generador de reportes y fin de la simulacion
report(outfile, multi);
fclose(inpfile);
fclose(outfile);
fclose(timfile);
fclose(tsfile);
fclose(qfile);
fclose(sfile);
fclose(dqfile);
fclose(stfile);
fclose(multi);

%	tevents = [tevents time];
%	cqueue = [cqueue num_in_q];
%	pstate = [pstate server_status];
%tevents(1:10)
%cqueue(1:10)
j=1;
for i=1:min(10, length(tevents))
	x(j) = tevents(j);
	y(j) = cqueue(j);
	if (event_types(j) == 1)
		i++;
	endif
	j++;
endfor

clf;
stairs(x,y);
xlabel("Tiempo (s)");
ylabel("Clientes en cola en el instante t");
title("Cantidad de clientes en la cola en cada instante");
axis([min(x) max(x) min(y) (max(y)+0.5)]);
print([name 'qvst.eps'], '-deps');

clf;
plot(tevents,event_types,"-");
hold on;
axis([min(tevents) max(tevents) 0.5 2.5]);
hold off;
print([name 'timesevents.eps'], '-deps');

return;
endfunction
